//
//  AppDelegate.swift
//  Practice
//
//  Created by miaozhihui on 2016/11/18.
//  Copyright © 2016年 DeKuTree. All rights reserved.
//

import UIKit
import AFNetworking
import UserNotifications
import SVProgressHUD

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        // 三方库默认设置
        setupDefaultInfo()
        
        // 通知 用户授权 设置
        notificationAuthorization(application: application)
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        window?.rootViewController = MainViewController()
        window?.makeKeyAndVisible()
        
        loadAppInfo()
        
        return true
    }
}

// MARK: - 从服务器加载应用程序信息
extension AppDelegate {
    
    fileprivate func loadAppInfo() {
        
        // 模拟异步加载网络数据
        DispatchQueue.global().async {
            
            let url = Bundle.main.url(forResource: "main", withExtension: "json")
            
            let data = NSData(contentsOf: url!)
            
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
            
            data?.write(toFile: jsonPath, atomically: true)
            
            print("应用程序加载完毕 \(jsonPath)")
        }
    }
}

// MARK: - 用户授权相关
extension AppDelegate {
    
    /// 通知授权
    fileprivate func notificationAuthorization(application:UIApplication) {
        
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound,.carPlay]) { (isSuccess, error) in
                print("授权" + (isSuccess ? "成功" : "失败"))
            }
        } else {
            let notifySettings = UIUserNotificationSettings(types: [.alert,.badge,.sound], categories: nil)
            application.registerUserNotificationSettings(notifySettings)
        }
    }
    
}

// MARK: - 三方库一些默认设置
extension AppDelegate {
    
    fileprivate func setupDefaultInfo() {
        // 设置提示框显示时间
        SVProgressHUD.setMinimumDismissTimeInterval(2)
        // 设置网络加载指示器(状态条上显示加载指示器)
        AFNetworkActivityIndicatorManager.shared().isEnabled = true
    }
}
